package com.itheima.youdianda.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.intern.InternUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.youdianda.common.BaseContext;
import com.itheima.youdianda.common.R;
import com.itheima.youdianda.dto.*;
import com.itheima.youdianda.exception.CommonException;
import com.itheima.youdianda.mapper.IndexMapper;
import com.itheima.youdianda.pojo.*;
import com.itheima.youdianda.service.*;
import com.itheima.youdianda.utils.AppJwtUtil;
import com.itheima.youdianda.vo.HotListVo;
import com.itheima.youdianda.vo.Hotvo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class IndexServiceImpl extends ServiceImpl<IndexMapper, SysUser> implements IndexService {
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysDictService sysDictService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private YddCateService yddCateService;
    @Autowired
    private YddArticleService yddArticleService;
    @Autowired
    private YddadvposService yddadvposService;
    @Autowired
    private YddTagService yddTagService;
    @Autowired
    private YddAdvimgService yddAdvimgService;
    @Autowired
    private YddUserService yddUserService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private YddLinkService yddLinkService;

    @Override
    public R login(Map<String, String> map) {
        String username = map.get("login_name");
        if (username == null) {
            throw new CommonException("用户未登录");
        }
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysUser::getLoginName, username);
        SysUser sysUser = getOne(lqw);

        if (sysUser == null) {
            return R.error("用户名不存在");
        }
        if (!Objects.equals(sysUser.getPassword(), DigestUtils.md5DigestAsHex(map.get("password").getBytes()))) {
            return R.error("密码错误");
        }
        if (sysUser.getStatus() != 1) {
            return R.error("账号被禁用");
        }

        //todo:临时获取用户id
//        request.getSession().setAttribute("id", sysUser.getId());

        String token = AppJwtUtil.getToken(sysUser.getId());
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);

        //更新登录时间,todo:ip未设置

        sysUser.setLoginDate(LocalDateTime.now());
//        sysUser.setRoleId("be0e2540-3c49-11ec-abdc-7ba81cf6c5ef");
        sysUser.setRoleId(sysUser.getRoleId());

        update(sysUser, lqw);
        return R.success(tokenMap);
    }

    @Override
    public R getConfig() {
        LambdaQueryWrapper<SysConfig> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysConfig::getTabValue, "system");
        List<SysConfig> list = sysConfigService.list(lqw);
        Map<String, String> map = new HashMap<>();
        for (SysConfig sysConfig : list) {
            map.put(sysConfig.getAttrKey(), sysConfig.getAttrValue());
        }

        return R.success(map);
    }

    /**
     * 首页数据
     *
     * @return
     */
    @Override
    public R baseInfo() {
        BaseInfoDto baseInfoDto = new BaseInfoDto();
        //所有分类数据
        List<YddCate> yddCates = yddCateService.list();
        //获取对应分类下的文章数量
        for (YddCate yddCate : yddCates) {
            LambdaQueryWrapper<YddArticle> yddLqw = new LambdaQueryWrapper<>();
            yddLqw.eq(YddArticle::getCateid, yddCate.getId());
            List<YddArticle> articles = yddArticleService.list(yddLqw);
            yddCate.setNum(articles.size());
        }
        baseInfoDto.setAll_cate(yddCates);

        //获取广告位数量
        List<YddAdvpos> advposList = yddadvposService.list();
        baseInfoDto.setAdvpos_num(advposList.size());
        //标签总数
        List<YddTag> tagList = yddTagService.list();
        baseInfoDto.setTag_num(tagList.size());
        //管理员总数
        List<SysUser> userList = sysUserService.list();
        baseInfoDto.setAdmin_num(userList.size());
        //文章总数
        List<YddArticle> articleList = yddArticleService.list();
        baseInfoDto.setArticle_num(articleList.size());
        //分类总数
        baseInfoDto.setCate_num(yddCates.size());
        //广告图总数
        List<YddAdvimg> yddAdvimgList = yddAdvimgService.list();
        baseInfoDto.setAdvimg_num(yddAdvimgList.size());

        //最新用户信息
        Page page = new Page(1, 7);
        LambdaQueryWrapper<YddUser> userLqw = new LambdaQueryWrapper<>();
        userLqw.orderByDesc(YddUser::getId);
//        List<YddUser> yddUserList = yddUserService.list(userLqw);
        Page pageInfo = yddUserService.page(page, userLqw);
        List<YddUser> yddUserList = pageInfo.getRecords();
        baseInfoDto.setNew_user(yddUserList);

        //热门文章数据
        LambdaQueryWrapper<YddArticle> articleLqw = new LambdaQueryWrapper<>();
        articleLqw.orderByDesc(YddArticle::getLovenum);
        List<YddArticle> yddArticleList = yddArticleService.list(articleLqw);
        baseInfoDto.setHot_article(yddArticleList);

        //用户数据
        LambdaQueryWrapper<YddUser> yddLqw = new LambdaQueryWrapper<>();
        List<YddUser> list = yddUserService.list(yddLqw);
        yddLqw.eq(YddUser::getSex, 1);
        List<YddUser> manList = yddUserService.list(yddLqw);
        UserNumDto userNumDto = new UserNumDto();
        userNumDto.setTotal(list.size());
        userNumDto.setUser_man(manList.size());
        userNumDto.setUser_woman(list.size() - manList.size());
        baseInfoDto.setUser(userNumDto);

        return R.success(baseInfoDto);
    }

    @Override
    public R profile() {
//        String id = request.getSession().getAttribute("id").toString();
        String id = BaseContext.getId();
        //userInfo
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(id != null, SysUser::getId, id);
        SysUser userInfo = getOne(lqw);

        //menuList
        List<SysMenu> menuList = sysMenuService.list();

        //dictsList
        DictsListDto dictsListDto = new DictsListDto();

        List<SysDict> list = sysDictService.list();
        for (SysDict sysDict : list) {
            String type = sysDict.getType();
            LambdaQueryWrapper<SysDict> dictLqw = new LambdaQueryWrapper<>();
            dictLqw.eq(SysDict::getType, type);
            List<SysDict> dicts = sysDictService.list(dictLqw);

//            Map<String, String> map = new HashMap<>();
//            for (SysDict dict : dicts) {
//                map.put(dict.getValue(), dict.getLabel());
//            }
            if (type.equals("interface_type")){
                Map<String, String> map = new HashMap<>();
                for (SysDict dict : dicts) {
                    map.put(dict.getValue(), dict.getLabel());
                }
                Interface_typeDto interface_typeDto = new Interface_typeDto();
                interface_typeDto.setGet("get");
                interface_typeDto.setPost("post");
                dictsListDto.setInterface_type(interface_typeDto);
            }
            if (type.equals("order_type")){
                Map<Integer, String> map = new HashMap<>();
                for (SysDict dict : dicts) {
                    map.put(Convert.toInt(dict.getValue()), dict.getLabel());
                }
                dictsListDto.setOrder_type(map);
            }
            if (type.equals("report_type")){
                Map<Integer, String> map = new HashMap<>();
                for (SysDict dict : dicts) {
                    map.put(Convert.toInt(dict.getValue()), dict.getLabel());
                }
                dictsListDto.setReport_type(map);
            }
            if (type.equals("table_type")){
                Map<Integer, String> map = new HashMap<>();
                for (SysDict dict : dicts) {
                    map.put(Convert.toInt(dict.getValue()), dict.getLabel());
                }
                dictsListDto.setTable_type(map);
            }
            if (type.equals("theme")){
                Map<String, String> map = new HashMap<>();
                for (SysDict dict : dicts) {
                    map.put(dict.getValue(), dict.getLabel());
                }
                ThemeDto themeDto = new ThemeDto();
                themeDto.setAce("ACE风格");
                dictsListDto.setTheme(themeDto);
            }

//            dictsList.add(dictMap);
        }
        //todo:btnList

        ProfileDto profileDto = new ProfileDto();
        profileDto.setUserInfo(userInfo);
        profileDto.setMenuList(menuList);
        List btnList = new ArrayList();
        btnList.add("*");
        profileDto.setBtnList(btnList);
        profileDto.setDictsList(dictsListDto);
        return R.success(profileDto);
    }


    @Override
    public R frontPage(Integer page, Integer limit) {
        Page<YddArticle> yddArticlePage = new Page<>(page, limit);
        yddArticleService.page(yddArticlePage);
        return R.success(yddArticlePage);
    }

    @Override
    public R articleList(Integer page, Integer limit, Integer cateid) {
        Page<YddArticle> yddArticlePage = new Page<>(page, limit, cateid);
        yddArticleService.page(yddArticlePage);
        List<YddArticle> yddArticleList = yddArticlePage.getRecords();

        //填充数据
        for (YddArticle yddArticle : yddArticleList) {
            Integer cateId = yddArticle.getCateid();
            LambdaQueryWrapper<YddCate> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(cateId != null, YddCate::getId, cateId);
            YddCate yddCate = yddCateService.getOne(wrapper);
            yddArticle.setCatename(yddCate.getCatename());
        }
        yddArticlePage.setRecords(yddArticleList);
        return R.success(yddArticlePage);
    }

    //推荐
    @Override
    public R recommend() {

        Hotvo hotvo = new Hotvo();
        HotListVo hotListVo = new HotListVo();
        ArrayList<HotListVo> hotListVos = new ArrayList<>();

        //根据ishot来进行条件选择   ishot 为一的时候比较热们
        LambdaQueryWrapper<YddArticle> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(YddArticle::getIshot,1);
        wrapper.last("limit 6");
        //将yddArticle的值封装到hotListVo中
        List<YddArticle> yddArticleList = yddArticleService.list(wrapper);
        for (YddArticle yddArticle : yddArticleList) {
            Integer cateid = yddArticle.getCateid();
            YddCate yddCate = yddCateService.getById(cateid);
             hotListVo.setCatename(yddCate.getCatename());
             hotListVo.setId(yddArticle.getId());
             hotListVo.setPic(yddArticle.getPic());
             hotListVo.setTitle(yddArticle.getTitle());
             hotListVo.setLovenum(yddArticle.getLovenum());
             hotListVos.add(hotListVo);
        }
        hotvo.setDesc("侧边推荐文章");
        hotvo.setList(hotListVos);
        return R.success(hotvo);
    }


    //侧边最新文章
    @Override
    public R hot() {
        Hotvo hotvo = new Hotvo();
        HotListVo hotListVo = new HotListVo();
        List<HotListVo> hotListVos = new ArrayList<>();



        // 根据时间进行条件排序 分页查询第一页的六条数据
        //Page pageInfo = new Page(1,6);
        //根据时间进行排序选择最上面的6个数据
        LambdaQueryWrapper<YddArticle> wrapper=new LambdaQueryWrapper<>();
        //将yddArticle的值封装到hotListVo中
       // wrapper.orderByDesc(YddArticle::getUpdateDate);
        wrapper.between(true,YddArticle::getUpdateDate,LocalDateTime.now(),LocalDateTime.now().minusDays(1));
        //wrapper.between(LocalDateTime.now(),)
        //获取最上面的6条数据



        List<YddArticle> yddArticleList = yddArticleService.list(wrapper);

        for (YddArticle yddArticle : yddArticleList) {
            Integer cateid = yddArticle.getCateid();
            YddCate yddCate = yddCateService.getById(cateid);
            hotListVo.setCatename(yddCate.getCatename());
            hotListVo.setId(yddArticle.getId());
            hotListVo.setPic(yddArticle.getPic());
            hotListVo.setTitle(yddArticle.getTitle());
            hotListVo.setLovenum(yddArticle.getLovenum());
            hotListVos.add(hotListVo);
        }
        hotvo.setDesc("侧边最新文章");
        hotvo.setList(hotListVos);
        return R.success(hotvo);
    }

    @Override
    public Object show(String id) {
        return null;
    }

    @Override
    public R index() {
        List<YddCate> allCate = yddCateService.list();
        List<YddLink> allLink = yddLinkService.list();
        List<YddTag> allTag = yddTagService.list();
        List<SysConfig> sysConfigList = sysConfigService.list();

        LambdaQueryWrapper<YddAdvimg> qw1 = new LambdaQueryWrapper<>();
        qw1.eq(YddAdvimg::getAdvimgsrc, 15);
        List<YddAdvimg> banner = yddAdvimgService.list(qw1);

        LambdaQueryWrapper<YddAdvimg> qw2 = new LambdaQueryWrapper<>();
        qw2.eq(YddAdvimg::getAdvimgsrc, 13);
        List<YddAdvimg> showBanner = yddAdvimgService.list(qw2);

        LambdaQueryWrapper<YddAdvimg> qw3 = new LambdaQueryWrapper<>();
        qw3.eq(YddAdvimg::getAdvimgsrc, 14);
        List<YddAdvimg> sideBanner = yddAdvimgService.list(qw3);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("allCate",allCate);
        hashMap.put("allLink",allLink);
        hashMap.put("allTag",allTag);
        hashMap.put("banner",banner);
        hashMap.put("config",sysConfigList);
        hashMap.put("showBanner",showBanner);
        hashMap.put("sideBanner",sideBanner);

        return R.success(hashMap);

    }
}
